package hibernateDAOS;

import hibernate.HibernateUtil;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;


import beans.Proveedor;

public class ProveedorDAO {
	
	private static ProveedorDAO instancia = null;
	private static SessionFactory sf = null;

	public static ProveedorDAO getInstancia(){
		if(instancia == null){
			sf = HibernateUtil.getSessionFactory();
			instancia = new ProveedorDAO();
		} 
		return instancia;
	}
	
	public void guardarProveedor(Proveedor p){
		Session session = sf.openSession();
		session.beginTransaction();
		session.save(p);
		session.flush();
		session.getTransaction().commit();
		session.close();
	}

	public void eliminarProveedor(Proveedor p){
		Session session = sf.openSession();
		session.beginTransaction();
		session.delete(p);
		session.flush();
		session.getTransaction().commit();
		session.close();
	}

	public void modificarProveedor(Proveedor p){
		Session session = sf.openSession();
		session.beginTransaction();
		session.saveOrUpdate(p);
		session.flush();
		session.getTransaction().commit();
		session.close();
	}

	@SuppressWarnings("unchecked")
	public List<Proveedor> obtenerProveedores(){
		Session session = sf.openSession();
		Query q = session.createQuery("from Proveedor");
		List<Proveedor> proveedores = q.list();
		session.close();
		return proveedores;
	}

	public Proveedor obtenerProveXNombre(String nombProve)
	{
		Session session = sf.openSession();
		Query q = session.createQuery("from Proveedor pr where pr.nombre = :nombProve ").setParameter("nombProve", nombProve);
		Proveedor pr = (Proveedor) q.uniqueResult();
		session.close();
		return pr;
	}
}


